import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';


// 时间 和 日期
class DateAndTimePickerFormForm extends StatefulWidget {

    final dynamic controller;      // 表单名称
    final String label;           // lable
    final bool validator;         // 校验
    final String validatorText;   // 校验提示
    final bool readOnly;          // 只读
    final dynamic onChanged;    // 值改变

    final DateTime firstDate; // 开始日期
    final DateTime lastDate; // 结束日期
    final dynamic formatDate; // 日期格式化

    DateAndTimePickerFormForm({
        Key key,
        this.controller,
        this.label,
        this.validator=false,
        this.validatorText="必填",
        this.readOnly=false,   
        this.onChanged,
        this.firstDate,
        this.lastDate,   
        this.formatDate,        
        
    }) : super(key: key);  

    @override
    _DateAndTimePickerFormFormState createState() => new _DateAndTimePickerFormFormState();
}

class _DateAndTimePickerFormFormState extends State<DateAndTimePickerFormForm> {


    // 初始化
    void initState() {
      super.initState();      
    }

    @override
    void dispose() {
      super.dispose();
    }

    // 保存时间
    void _saveFunc(_date,_time){
      String _text="${_date.toString()} ${_time.toString()}";
      widget.controller.text=_text;

      // 回调
      if( widget.onChanged!=null ){
         widget.onChanged(_text); 
      } 

    }

    // 弹框
    void _dialogFunc(context){

        showDialog<Null>(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context){

              String bufferDate= (widget.controller.text!=null && widget.controller.text!='')?widget.controller.text.split(" ")[0] :"";   // 缓存日期
              String bufferTime= (widget.controller.text!=null && widget.controller.text!='')?widget.controller.text.split(" ")[1] :"";   // 缓存时间

              return StatefulBuilder(
                builder: (context, state) {
                  return AlertDialog(
                      title: Text('日期和时间'),
                      content: SingleChildScrollView(
                          child: ListBody(
                              children: <Widget>[
                                Row(
                                  children: <Widget>[
                                    RaisedButton(
                                      color: Colors.blue,
                                      textColor: Colors.white,
                                      child: Text('选择日期'),
                                      onPressed: () async{
                                        var _date= await this._changeDate(context);

                                        if( _date!=null ){
                                          state(() {
                                            bufferDate=_date;
                                          }); 
                                        }

                                        // 补时间
                                        if( bufferTime=='' ){
                                          state(() {
                                            bufferTime="00:00";
                                          }); 
                                        }
                                      },
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.fromLTRB(16,0,6,0),
                                      child: Text("$bufferDate"),
                                    )
                                  ],
                                ),
                                Row(
                                  children: <Widget>[
                                    RaisedButton(
                                      color: Colors.blue,
                                      textColor: Colors.white,
                                      child: Text('选择时间'),
                                      onPressed: () async{
                                        var _time= await this._changeTime(context);
                                        
                                        if( _time!=null ){
                                          state(() {
                                            bufferTime=_time;
                                          }); 
                                        }

                                        // 补日期
                                        if( bufferDate=='' ){
                                          state(() {
                                            bufferDate=formatDate(DateTime.now(),[yyyy,"-",mm,"-",dd]);
                                          }); 
                                        }

                                      },
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.fromLTRB(16,0,6,0),
                                      child: Text("$bufferTime"),
                                    )
                                  ],
                                )                              
                              ]
                          ),
                      ),
                      actions: <Widget>[
                        FlatButton(
                          child: Text('取消'),
                          onPressed:(){
                            Navigator.of(context).pop(); 
                          }
                        ),                        
                        FlatButton(
                          child: Text('确定'),
                          color: Colors.blue,
                          onPressed: () {
                            this._saveFunc(bufferDate,bufferTime);  // 保存时间
                            Navigator.of(context).pop();
                          },
                        ),
                      ],
                  );
                }
              );              
            },
        ).then((val) {
            print(val);
        }); 

    }


    // 选择 日期
    dynamic _changeDate(context) async{

      dynamic _date = await showDatePicker(
        context: context,
        helpText: '请选择日期',
        // initialDate:DateTime.now(),
        initialDate: (widget.controller.text!='' && widget.controller.text!=null )?
          DateTime.parse( (widget.controller.text.split(" ")[0]) )
          :DateTime.now(),
        firstDate: (widget.firstDate!=null)?widget.firstDate:DateTime(1970,1,1),
        lastDate: (widget.lastDate!=null)?widget.lastDate:DateTime(2070,1,1),
      );  

      if( _date==null ) return null;
      return formatDate(_date, [yyyy,"-",mm,"-",dd]);
    }

    
    // 选择 时间
    dynamic _changeTime(context) async{

        dynamic _time  = await showTimePicker(
          context: context,
          builder: (BuildContext context, Widget child) {
            return MediaQuery(
              data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
              child: child,
            );
          },          
          initialTime: (widget.controller.text!=''&& widget.controller.text!=null) ? 
            TimeOfDay(
              hour: int.parse( (widget.controller.text.split(" ")[1]).split(":")[0] ),
              minute: int.parse( (widget.controller.text.split(" ")[1]).split(":")[1] )
            )
            :TimeOfDay.now(),
      );   

      if( _time==null ) return null;
      return this._formatTime(_time);
    }  

    // 时间格式化 
    String _formatTime(val){

      var hour;
      var minute;

      // 补零
      hour= (val.hour<10) ? '0${val.hour}':'${val.hour}';
      minute= (val.minute<10) ? '0${val.minute}':'${val.minute}';

      return '${hour.toString()}:${minute.toString()}';
    }


    @override
    Widget build(BuildContext context) {
        return Padding(
          padding: EdgeInsets.fromLTRB(16,32,16,16),
          child:  Container(
            // color: Colors.white,
            child: Stack(
                children: <Widget>[

                  Container(
                    // padding: EdgeInsets.fromLTRB(0,0,0,16),
                    child: Row(
                      children: <Widget>[

                        Text(
                          widget.validator?'*':'',
                          textAlign: TextAlign.left,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: 14,
                              color: Colors.red
                          )
                        ),  

                        Text(
                          widget.label.toString(),
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: 14,
                              color: const Color.fromRGBO(81,90,110,1)
                          ),
                        )
                      ],
                    ),
                  ),


                  Container(
                    margin: EdgeInsets.fromLTRB(0,26,0,0),
                    child: Row(
                      children: <Widget>[
                          Expanded(
                            child: TextFormField(
                              controller: widget.controller,
                              autofocus: false,
                              readOnly: true,
                              style: TextStyle(
                                color: Colors.transparent,
                              ),
                              decoration: InputDecoration(
                                  fillColor: Colors.black.withOpacity(0.05),
                                  filled: widget.readOnly,                                 
                                  // labelText: widget.label,
                                  labelStyle: TextStyle( 
                                      fontSize: 14.0, 
                                      color: Color.fromARGB(255, 93, 93, 93)
                                  ),
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(width:0.5,color: Colors.grey[500]),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(width:0.5,color: Colors.blue),
                                  ),
                                  errorBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(width:0.5,color: Colors.red),
                                  ),                                    
                              ),
                              validator: widget.validator ? (value) {
                                if (value.isEmpty) {
                                  return widget.validatorText;
                                }
                                return null;
                              }:null,
                            )
                          )
                      ],
                    ),
                  ),

                  InkWell(
                    onTap: (){
                      if( !widget.readOnly ){
                        FocusScope.of(context).requestFocus(FocusNode());

                        this._dialogFunc(context);
                      }
                    },  
                    child: Container(
                      margin: EdgeInsets.fromLTRB(12,15,0,0),
                      height: 50,
                      child: Row(
                        children: <Widget>[
                          Padding(
                            padding: const EdgeInsets.fromLTRB(0,24,0,0),
                            child:(widget.controller.text!='')? Text(
                              '${widget.controller.text}',
                              style: TextStyle(
                                fontSize: 16.0, 
                                // height: 1.5,
                              ),
                            ):null
                          )
                        ],
                      ),
                    ) 
                  )  
                 
                ]
            )   
          )  
        );
    }  
}


